package infra

import (
	"errors"

	"gitee.com/h2ob/base"
	"github.com/gin-gonic/gin/binding"
)

type Code2SessionRsp struct {
	SessionKey string `json:"session_key"`
	Unionid    string `json:"unionid"`
	Openid     string `json:"openid"`
	Msg        string `json:"errmsg"`
	Code       int    `json:"errcode"`
}

func VerifyCode(code string) (*Code2SessionRsp, error) {
	baseUrl := "https://api.weixin.qq.com/sns/jscode2session"
	params := make(map[string]string)
	params["appid"] = base.GConf.Xcx.AppId
	params["secret"] = base.GConf.Xcx.Token
	params["js_code"] = code
	params["grant_type"] = "authorization_code"
	rb, err := doGet(baseUrl, params, nil)
	if err != nil {
		base.GLogger.Infof("verify code error:%s", err)
		return nil, err
	}
	csr := Code2SessionRsp{}
	err = binding.JSON.BindBody(rb, &csr)
	if err != nil {
		base.GLogger.Warnf("Parser Request err:%s", err.Error())
		return nil, err
	}

	if csr.Code != 0 {
		base.GLogger.Infof("Code2Session failed:%s", csr.Msg)
		return nil, errors.New(csr.Msg)
	}
	return &csr, nil
}
